/*
 * Copyright (c) Ulrich Hilger, http://dev.uhilger.de, all rights reserved.
 *
 * Published under the terms and conditions of the Apache License 2.0,
 * see http://www.apache.org/licenses/LICENSE-2.0
 */

package de.uhilger.servicehub.server;

import de.uhilger.servicehub.model.ServletContainer;
import de.uhilger.util.InfoThread;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.JDBCLoginService;
import org.eclipse.jetty.server.handler.HandlerList;

/**
 * Start Jetty in an own thread.
 *
 * @author Ulrich Hilger, <a href="http://dev.uhilger.de" target="_blank">http://dev.uhilger.de</a>
 * @author Published under the terms and conditions of
 * the <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License 2.0</a>
 */
public class StartJettyThread extends InfoThread {

  private EmbeddedJetty jetty;
  private org.eclipse.jetty.server.Server server;
  private boolean workIsLeft = false;
  private String base;

  public StartJettyThread(EmbeddedJetty jetty) {
    this.jetty = jetty;
  }

  @Override
  protected void prepareThread() {

  }

  @Override
  protected boolean stopWorker() {
    try {
      server.stop();
    } catch (Exception ex) {
      Logger.getLogger(StartJettyThread.class.getName()).log(Level.SEVERE, null, ex);
    }
    workIsLeft = false;
    return true;
  }

  @Override
  protected boolean work() {
    try {
      server = new org.eclipse.jetty.server.Server(jetty.getPort());
      JDBCLoginService jdbcLoginService = new JDBCLoginService();
      jdbcLoginService.setConfig(jetty.getBase() + "/conf/jdbcRealm.properties");
      //ConstraintSecurityHandler secHandler = new ConstraintSecurityHandler();
      //secHandler.setLoginService(jdbcLoginService);

      String webappsPath = base + ServletContainer.URL_SEPARATOR + ServletContainer.DEFAULT_WEBAPPS_PATH;
      File webappsDir = new File(webappsPath);
      File[] contextDir = webappsDir.listFiles();
      HandlerList handlers = new HandlerList();
      if(contextDir != null) {
        for(int i = 0; i < contextDir.length; i++) {
          if(contextDir[i].isDirectory()) {
            //Context context = null;
            String contextPath = ServletContainer.URL_SEPARATOR + contextDir[i].getName();
            if(contextPath.endsWith(ServletContainer.DEFAULT_ROOT)) {
              contextPath = "";
            }
            //String docBase = webappsPath + EmbeddedTomcat.URL_SEPARATOR + contextDir[i].getName();
            //context = embeddedServer.createContext(contextPath, docBase);
            //context.setPrivileged(true);
            //localhost.addChild(context);
            org.eclipse.jetty.webapp.WebAppContext webapp = new org.eclipse.jetty.webapp.WebAppContext();
            webapp.setContextPath(contextPath);
            ConstraintSecurityHandler secHandler = new ConstraintSecurityHandler();
            secHandler.setLoginService(jdbcLoginService);
            webapp.setSecurityHandler(secHandler);
            String docBase = webappsPath + contextPath;
            System.out.println("set jetty app to war " + docBase);
            webapp.setWar(docBase);
            handlers.addHandler(webapp);
            System.out.println("Jetty start thread setting session path " + webappsPath + " for " + contextPath);
            webapp.getSessionHandler().getSessionManager().setSessionPath(webappsPath);
          }
        }
      }

      if(handlers.getHandlers().length > 0) {
        server.setHandler(handlers);
      }

      /*
      ContextDeployer deployer = new ContextDeployer();
      deployer.setContextsDir(base + File.separator + "conf/deployment_temp");
      deployer.setContexts(new ContextHandlerCollection());
      deployer.setScanInterval(5);
      server.addBean(deployer);
      */

      /*
      org.eclipse.jetty.webapp.WebAppContext webapp = new org.eclipse.jetty.webapp.WebAppContext();
      webapp.setSecurityHandler(secHandler);
      webapp.setContextPath("/AudioHub");
      System.out.println("set jetty app to war " + jetty.getBase() + "/webapps/AudioHub.war");
      webapp.setWar(jetty.getBase() + "/webapps/AudioHub");
      server.setHandler(webapp);
       */
      jetty.setServer(server);
      server.start();
      server.join();
    } catch (Exception ex) {
      Logger.getLogger(StartJettyThread.class.getName()).log(Level.SEVERE, null, ex);
    }
    return workIsLeft;
  }

  public void setBase(String base) {
    this.base = base;
  }
}
